<!-- build time:Tue Jul 21 2020 12:41:25 GMT+0800 (GMT+08:00) --><!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><meta name="generator" content="Hexo 4.2.0"><link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png"><link rel="icon" type="image/png" sizes="32x32" href="/img/blog_favicon/favicon-32x32-next.png"><link rel="icon" type="image/png" sizes="16x16" href="/img/blog_favicon/favicon-16x16-next.png"><link rel="mask-icon" href="/images/logo.svg" color="#222"><meta name="baidu-site-verification" content="r15J5zOS2KI43yBS"><link rel="stylesheet" href="/css/main.css"><link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"><link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css"><link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/themes/blue/pace-theme-minimal.min.css"><script src="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.min.js"></script><script id="hexo-configurations">var NexT=window.NexT||{},CONFIG={hostname:new URL("http://www.zhengjiaao.cn").hostname,root:"/",scheme:"Muse",version:"7.6.0",exturl:!1,sidebar:{position:"left",display:"post",padding:18,offset:12,onmobile:!1},copycode:{enable:!0,show_result:!0,style:null},back2top:{enable:!0,sidebar:!1,scrollpercent:!0},bookmark:{enable:!0,color:"#222",save:"auto"},fancybox:!0,mediumzoom:!1,lazyload:!1,pangu:!1,comments:{style:"tabs",active:"valine",storage:!0,lazyload:!1,nav:null,activeClass:"valine"},algolia:{appID:"",apiKey:"",indexName:"",hits:{per_page:10},labels:{input_placeholder:"Search for Posts",hits_empty:"We didn't find any results for the search: ${query}",hits_stats:"${hits} results found in ${time} ms"}},localsearch:{enable:!0,trigger:"auto",top_n_per_article:1,unescape:!1,preload:!1},path:"search.xml",motion:{enable:!0,async:!1,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}}}</script><meta property="og:type" content="article"><meta property="og:title" content="Hibernate-关联时的问题及解决"><meta property="og:url" content="http://www.zhengjiaao.cn/posts/3750386836.html"><meta property="og:site_name" content="宇宙小神特别萌"><meta property="og:locale" content="zh_CN"><meta property="og:image" content="https://upload-images.jianshu.io/upload_images/15645795-193338a0822629d9.png"><meta property="og:image" content="https://upload-images.jianshu.io/upload_images/15645795-a0373388bd292724.png"><meta property="og:image" content="https://upload-images.jianshu.io/upload_images/15645795-c3638236b4002640.png"><meta property="article:published_time" content="2020-01-03T08:14:49.000Z"><meta property="article:modified_time" content="2020-07-20T10:37:55.303Z"><meta property="article:author" content="宇宙小神特别萌"><meta property="article:tag" content="Hibernate"><meta name="twitter:card" content="summary"><meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/15645795-193338a0822629d9.png"><link rel="canonical" href="http://www.zhengjiaao.cn/posts/3750386836.html"><script id="page-configurations">CONFIG.page={sidebar:"",isHome:!1,isPost:!0}</script><title>Hibernate-关联时的问题及解决 | 宇宙小神特别萌</title><noscript><style>.sidebar-inner,.use-motion .brand,.use-motion .collection-header,.use-motion .comments,.use-motion .menu-item,.use-motion .pagination,.use-motion .post-block,.use-motion .post-body,.use-motion .post-header{opacity:initial}.use-motion .site-subtitle,.use-motion .site-title{opacity:initial;top:initial}.use-motion .logo-line-before i{left:initial}.use-motion .logo-line-after i{right:initial}</style></noscript><link rel="alternate" href="/atom.xml" title="宇宙小神特别萌" type="application/atom+xml"></head><body itemscope itemtype="http://schema.org/WebPage"><div class="container use-motion"><div class="headband"></div><header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-container"><div class="site-meta custom-logo"><div class="site-meta-headline"><a><img class="custom-logo-image" src="/img/blog_favicon/favicon-32x32-next.png" alt="宇宙小神特别萌"></a></div><div><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">宇宙小神特别萌</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle">ZhengJa</p></div><div class="site-nav-toggle"><div class="toggle" aria-label="切换导航栏"><span class="toggle-line toggle-line-first"></span> <span class="toggle-line toggle-line-middle"></span> <span class="toggle-line toggle-line-last"></span></div></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">27</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">116</span></a></li><li class="menu-item menu-item-sitemap"><a href="/sitemap.xml" rel="section"><i class="fa fa-fw fa-sitemap"></i>站点地图</a></li><li class="menu-item menu-item-messageboard"><a href="/messageboard/" rel="section"><i class="fa fa-fw fa-address-book"></i>留言板</a></li><li class="menu-item menu-item-links"><a href="/links/" rel="section"><i class="fa fa-fw fa-user-plus"></i>友链</a></li><li class="menu-item menu-item-shuoshuo"><a href="/shuoshuo/" rel="section"><i class="fa fa-fw fa-file-text-o"></i>说说</a></li><li class="menu-item menu-item-search"><a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索</a></li></ul></nav><div class="site-search"><div class="popup search-popup"><div class="search-header"><span class="search-icon"><i class="fa fa-search"></i></span><div class="search-input-container"><input autocomplete="off" autocorrect="off" autocapitalize="none" placeholder="搜索..." spellcheck="false" type="text" id="search-input"></div><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span></div><div id="search-result"></div></div><div class="search-pop-overlay"></div></div></div></header><div class="back-to-top"><i class="fa fa-arrow-up"></i> <span>0%</span></div><div class="reading-progress-bar"></div><a role="button" class="book-mark-link book-mark-link-fixed"></a> <a href="https://github.com/zhengjiaao" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><main class="main"><div class="main-inner"><div class="content-wrap"><div class="content"><div class="posts-expand"><article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN"><link itemprop="mainEntityOfPage" href="http://www.zhengjiaao.cn/posts/3750386836.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/my-images/avatar.gif"><meta itemprop="name" content="宇宙小神特别萌"><meta itemprop="description" content="人生就是一次幸运的旅行！"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="宇宙小神特别萌"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">Hibernate-关联时的问题及解决</h1><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2020-01-03 16:14:49" itemprop="dateCreated datePublished" datetime="2020-01-03T16:14:49+08:00">2020-01-03</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="fa fa-calendar-check-o"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2020-07-20 18:37:55" itemprop="dateModified" datetime="2020-07-20T18:37:55+08:00">2020-07-20</time> </span><span id="/posts/3750386836.html" class="post-meta-item leancloud_visitors" data-flag-title="Hibernate-关联时的问题及解决" title="热度"><span class="post-meta-item-icon"><i class="fa fa-eye"></i> </span><span class="post-meta-item-text">热度：</span> <span class="leancloud-visitors-count"></span> <span>℃</span> </span><span class="post-meta-item" title="热度" id="busuanzi_container_page_pv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-eye"></i> </span><span class="post-meta-item-text">热度：</span> <span id="busuanzi_value_page_pv"></span> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="fa fa-comment-o"></i> </span><span class="post-meta-item-text">Valine：</span> <a title="valine" href="/posts/3750386836.html#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/posts/3750386836.html" itemprop="commentCount"></span></a></span><br><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="fa fa-file-word-o"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>13k</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="fa fa-clock-o"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>12 分钟</span></span></div></header><div class="post-body" itemprop="articleBody"><meta name="referrer" content="no-referrer"><a id="more"></a><p><img src="https://upload-images.jianshu.io/upload_images/15645795-193338a0822629d9.png" alt="Hibernate 关联时的问题及解决目录.png"></p><p>项目类型：spring5.x+hibernate5</p><h2 id="一、no-session-原因及解决"><a href="#一、no-session-原因及解决" class="headerlink" title="一、no session 原因及解决"></a>一、no session 原因及解决</h2><h4 id="1、原因：load-延迟查询引起noSession问题"><a href="#1、原因：load-延迟查询引起noSession问题" class="headerlink" title="1、原因：load()延迟查询引起noSession问题"></a>1、原因：load()延迟查询引起noSession问题</h4><p><strong>问题分析：</strong>对于根据id查询时 ，在dao通过load方式查询对象时 ，加载页面会报 noSession异常。当使用hibernate框架操作数据库的时候 ，如果做查询的话会有立即加载（get）和延迟加载（load）的区别 ，延迟加载表示 ，当你查询某个数据（假设是对象）的时候 ，hibernate不会立马发送sql语句 ，而是当我们调用这个对象的属性的时候 ，也就是真正使用查询出来的数据的时候才会发送sql语句去一级缓存（即session ，这里的session和域对象session没有半毛钱关系）中获取 ，但是正常这个session的开启核关闭是在service层执行的 ，但是我们真正使用查询的对象的数据时 ，是在web层 ，但是这个时候session已经关闭 ，就会报no-session异常。</p><p><img src="https://upload-images.jianshu.io/upload_images/15645795-a0373388bd292724.png" alt="noSession分析图"></p><p><strong>解决方式1：</strong>让session的关闭时间要在web层使用完之后。 但是web层已经是最后一层了 ，怎么办？还有比web更后的东西哦 ，就是过滤器 ， 所以在web.xml中配置开启和关闭session的过滤器即可 ，但是要配在strut或springmvc过滤器器之前 ，否则无效。</p><p>web.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--hibernate延迟加载,配置在所有filter之前(springmvc过滤器前) 解决无限循环和no Session问题 ，在get方法上使用@JsonBackReference--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">filter</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>hibernateFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-class</span>&gt;</span>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter<span class="tag">&lt;/<span class="name">filter-class</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>sessionFactoryBeanName<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>sessionFactory<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>hibernateFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dispatcher</span>&gt;</span>REQUEST<span class="tag">&lt;/<span class="name">dispatcher</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dispatcher</span>&gt;</span>FORWARD<span class="tag">&lt;/<span class="name">dispatcher</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure><p><img src="https://upload-images.jianshu.io/upload_images/15645795-c3638236b4002640.png" alt="添加过滤器解决noSession分析图"></p><p>使用load方法的解决方案 : 就是把原CustomerService层的绑定的session对象 提取配置到前面的 过滤器中了。</p><p><strong>解决方式2：</strong> load改用get立即加载方式查询对象。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 根据id获取用户信息-成功</span></span><br><span class="line"><span class="comment"> * 查询数据不存在 ，返回null,推荐使用, 不存在延迟加载问题 ，不采用lazy机制的</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> UserEntity <span class="title">getEntity</span><span class="params">(Integer id)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> hibernateTemplate.get(UserEntity<span class="class">.<span class="keyword">class</span>, <span class="title">id</span>)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * load查询单条数据 ，查询数据不存在 ，报异常(noSession) ，不推荐使用,存在延迟加载问题-失败</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> UserEntity <span class="title">loadEntity</span><span class="params">(Integer id)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> hibernateTemplate.load(UserEntity<span class="class">.<span class="keyword">class</span>, <span class="title">id</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="2、原因：没有开启使用注解事务-或者已经开启注解事务但并未使用"><a href="#2、原因：没有开启使用注解事务-或者已经开启注解事务但并未使用" class="headerlink" title="2、原因：没有开启使用注解事务(或者已经开启注解事务但并未使用)"></a>2、原因：没有开启使用注解事务(或者已经开启注解事务但并未使用)</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 注解方式(配置事物)：通过@Transactional启用事物管理 ，xml方式的配置会覆盖注解配置 --&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">tx:annotation-driven</span> <span class="attr">transaction-manager</span>=<span class="string">"transactionManager"</span> /&gt;</span></span><br></pre></td></tr></table></figure><p><strong>解决方式</strong>：开启注解事务并在需要事务环境的类中使用 ，@Transactional注解可以使用在类上 ，也可以使用在方法上</p><h4 id="3、原因：手动配置事务时-，propagation的值并未含有事务环境"><a href="#3、原因：手动配置事务时-，propagation的值并未含有事务环境" class="headerlink" title="3、原因：手动配置事务时 ，propagation的值并未含有事务环境"></a>3、原因：手动配置事务时 ，propagation的值并未含有事务环境</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 手动配置事务通知属性 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">tx:advice</span> <span class="attr">id</span>=<span class="string">"txAdvice"</span> <span class="attr">transaction-manager</span>=<span class="string">"transactionManager"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 定义事务传播属性 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">tx:attributes</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!--方法头--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"save*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"merge*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"insert*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"add*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"set*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"new*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"update*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"edit*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"remove*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"delete*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"execute*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"change*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"get*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span> <span class="attr">read-only</span>=<span class="string">"true"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"find*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span> <span class="attr">read-only</span>=<span class="string">"true"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"load*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span> <span class="attr">read-only</span>=<span class="string">"true"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span> <span class="attr">read-only</span>=<span class="string">"true"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">tx:attributes</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">tx:advice</span>&gt;</span></span><br></pre></td></tr></table></figure><p><strong>解决方式：</strong> 添加方法头 ，特别注意 ，将propagation值设置为REQUIRED</p><h2 id="二、懒加载出现死循环"><a href="#二、懒加载出现死循环" class="headerlink" title="二、懒加载出现死循环"></a>二、懒加载出现死循环</h2><p>懒加载出现死循环场景：多对多关联查询 ，多对一和一对多查询、自关联查询 等会出现对象死循环。</p><p><strong>原因：（你中有我 ，我中有你）</strong></p><p>具体分析 在于<strong>你要转化的对象里配置了对另外一个对象的关联 ，而那个对象里又配置了对你这个对象的关联 ，两个对象配置了双向的一对多和多对一的关联关系。</strong> JSON lib在把Dept部门对象转化为json字符串的时候 ，发现dept里有个Set&lt;Employee&gt; ，它就会去级联的把Set&lt;Employee&gt;转化为json字符串 ，在它遍历Set的时候 ，发现Employee员工里又有一个Dept部门对象 ，这时候它又会去尝试把dept转化为json字符串 ，然后就发现dept里又有Set&lt;Employee&gt; ，如此周而复始 ，就形成了死循环。</p><p>代码演示：一对多(部门对员工)、多对一(员工对部门)</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//员工</span></span><br><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Employee</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> empId;<span class="comment">// 员工的编号</span></span><br><span class="line">    <span class="keyword">private</span> String empName;<span class="comment">// 员工的名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span> salary;<span class="comment">// 员工的薪资</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Dept dept;<span class="comment">// 员工和部门的关系 </span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//部门</span></span><br><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dept</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> deptId;<span class="comment">// 部门编号</span></span><br><span class="line">    <span class="keyword">private</span> String deptName;<span class="comment">// 部门名称</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Set&lt;Employee&gt; emps;<span class="comment">// 部门对应多个员工 ，即一对多的关系</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Dept.hbm.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">	<span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">      第三写其他映射 ，比如这里的set集合映射 ，set集合映射主要有以下几点：</span></span><br><span class="line"><span class="comment">        1 实体类申明的集合属性属性（name）</span></span><br><span class="line"><span class="comment">        2 集合属性对应的表（table）</span></span><br><span class="line"><span class="comment">        3 指定集合表的外键字段名称（key中的column）</span></span><br><span class="line"><span class="comment">        4 集合对象对应的实体类（noe-to-many中的class）</span></span><br><span class="line"><span class="comment">        --&gt;</span></span><br><span class="line"><span class="comment">&lt;!--一对多(一个部门对应多个员工)--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">set</span> <span class="attr">name</span>=<span class="string">"emps"</span> <span class="attr">table</span>=<span class="string">"t_employee"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--column指定了员工表的外键字段名称 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">key</span> <span class="attr">column</span>=<span class="string">"deptId"</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- class由于上面已经写了包名 ，这里直接使用即可 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">one-to-many</span> <span class="attr">class</span>=<span class="string">"Employee"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">set</span>&gt;</span></span><br></pre></td></tr></table></figure><p>Employee.hbm.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">	<span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">    多对一的映射配置：多个员工对应一个部门</span></span><br><span class="line"><span class="comment">    name是实体类中申明的属性；</span></span><br><span class="line"><span class="comment">    column外键字段名称 ，对应多的一方的数据库表中的外键字段名；</span></span><br><span class="line"><span class="comment">    class对应的部门实体类；</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">many-to-one</span> <span class="attr">name</span>=<span class="string">"dept"</span> <span class="attr">column</span>=<span class="string">"deptId"</span> <span class="attr">class</span>=<span class="string">"Dept"</span>/&gt;</span></span><br></pre></td></tr></table></figure><p>出现死循环：用浏览器访问显示</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="string">"deptId"</span> : <span class="number">1</span>, <span class="string">"deptName"</span> : <span class="string">"人事部"</span>, <span class="string">"emps"</span> : [ &#123; <span class="string">"empId"</span> : <span class="number">1</span>, <span class="string">"empName"</span> : <span class="string">"员工1"</span>, <span class="string">"salary"</span> : <span class="number">1000.0</span>, <span class="string">"dept"</span> : &#123; <span class="string">"deptId"</span> : <span class="number">1</span>, <span class="string">"deptName"</span> : <span class="string">"人事部"</span>, <span class="string">"emps"</span> : [ &#123; <span class="string">"empId"</span> : <span class="number">1</span>, <span class="string">"empName"</span> : <span class="string">"员工1"</span>, <span class="string">"salary"</span> : <span class="number">1000.0</span>, <span class="string">"dept"</span> : &#123; <span class="string">"deptId"</span> : <span class="number">1</span>, <span class="string">"deptName"</span> : <span class="string">"人事部"</span>, <span class="string">"emps"</span> : [ &#123; <span class="string">"empId"</span> : <span class="number">1</span>, <span class="string">"empName"</span> : <span class="string">"员工1"</span>, <span class="string">"salary"</span> : <span class="number">1000.0</span>, <span class="string">"dept"</span> : &#123; <span class="string">"deptId"</span> : <span class="number">1</span>, <span class="string">"deptName"</span> : <span class="string">"人事部"</span>, <span class="string">"emps"</span> : [ &#123; <span class="string">"empId"</span> : <span class="number">1</span>, <span class="string">"empName"</span> : <span class="string">"员工1"</span>, <span class="string">"salary"</span> : <span class="number">1000.0</span>, <span class="string">"dept"</span> : &#123; <span class="string">"deptId"</span> : <span class="number">1</span>, <span class="string">"deptName"</span> : <span class="string">"人事部"</span>, <span class="string">"emps"</span> : [ &#123; <span class="string">"empId"</span> : <span class="number">1</span>, <span class="string">"empName"</span> : <span class="string">"员工1"</span>, <span class="string">"salary"</span> : <span class="number">1000.0</span>, <span class="string">"dept"</span> : &#123; <span class="string">"deptId"</span> : <span class="number">1</span>, <span class="string">"deptName"</span> : <span class="string">"人事部"</span>, <span class="string">"emps"</span> : [ &#123; <span class="string">"empId"</span> : <span class="number">1</span>, <span class="string">"empName"</span> : <span class="string">"员工1"</span>, <span class="string">"salary"</span> : <span class="number">1000.0</span>, <span class="string">"dept"</span> : &#123; <span class="string">"deptId"</span> : <span class="number">1</span>, <span class="string">"deptName"</span> : <span class="string">"人事部"</span>, <span class="string">"emps"</span> : [ &#123; <span class="string">"empId"</span> : <span class="number">1</span>, <span class="string">"empName"</span> : <span class="string">"员工1"</span>, <span class="string">"salary"</span> : <span class="number">1000.0</span>, <span class="string">"dept"</span> : &#123; <span class="string">"deptId"</span> : <span class="number">1</span>, <span class="string">"deptName"</span> : <span class="string">"人事部"</span>, <span class="string">"emps"</span> : [ &#123; <span class="string">"empId"</span> : <span class="number">1</span>, <span class="string">"empName"</span> : <span class="string">"员工1"</span>, <span class="string">"salary"</span> : <span class="number">1000.0</span>, <span class="string">"dept"</span> : &#123; <span class="string">"deptId"</span> : <span class="number">1</span>, <span class="string">"deptName"</span> : <span class="string">"人事部"</span>, <span class="string">"emps"</span> : [ &#123; <span class="string">"empId"</span> : <span class="number">1</span>, <span class="string">"empName"</span> : <span class="string">"员工1"</span>, <span class="string">"salary"</span> : <span class="number">1000.0</span>, <span class="string">"dept"</span> : &#123; <span class="string">"deptId"</span> : <span class="number">1</span>, <span class="string">"deptName"</span> : <span class="string">"人事部"</span>, <span class="string">"emps"</span> :</span><br></pre></td></tr></table></figure><p>后台出现异常：<strong>java.lang.StackOverflowError</strong> 死循环</p><p>要考虑两个大的方面:</p><ul><li><p>1.只有一方需要数据(如果你的业务单向关联就可以满足)</p></li><li><p>2.双方数据都需要的情况（如果你的业务必须使用双向关联）</p></li></ul><h3 id="1、只有一方需要数据"><a href="#1、只有一方需要数据" class="headerlink" title="1、只有一方需要数据"></a>1、只有一方需要数据</h3><p>解决思路：由于引起死循环查询的原因是序列化产生的 ，那么 ，针对序列化做处理 ，让不需要返回给前端的一方的对象不序列化。</p><h4 id="解决方式1：使用-JsonIgnore"><a href="#解决方式1：使用-JsonIgnore" class="headerlink" title="解决方式1：使用@JsonIgnore"></a>解决方式1：使用@JsonIgnore</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dept</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> deptId;<span class="comment">// 部门编号</span></span><br><span class="line">    <span class="keyword">private</span> String deptName;<span class="comment">// 部门名称</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@JsonIgnore</span> <span class="comment">//忽略 ，返回给前端时忽略此属性</span></span><br><span class="line">    <span class="keyword">private</span> Set&lt;Employee&gt; emps;<span class="comment">// 部门对应多个员工 ，即一对多的关系</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Employee</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> empId;<span class="comment">// 员工的编号</span></span><br><span class="line">    <span class="keyword">private</span> String empName;<span class="comment">// 员工的名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span> salary;<span class="comment">// 员工的薪资</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@JsonIgnore</span> <span class="comment">//忽略 ，返回给前端时忽略此属性</span></span><br><span class="line">    <span class="keyword">private</span> Dept dept;<span class="comment">// 员工和部门的关系</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><blockquote><p>注：不够友好 ，双方都要配置注解 ，若只配置一方 ，则另一方会报异常。</p></blockquote><p>效果：</p><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//查询部门信息</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="attr">"deptId"</span>:<span class="number">1</span>,</span><br><span class="line">	<span class="attr">"deptName"</span>:<span class="string">"人事部"</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//查询员工信息</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="attr">"empId"</span>:<span class="number">1</span>,</span><br><span class="line">	<span class="attr">"empName"</span>:<span class="string">"员工1"</span>,</span><br><span class="line">	<span class="attr">"salary"</span>:<span class="number">1000.0</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="解决方式2：使用fastjson"><a href="#解决方式2：使用fastjson" class="headerlink" title="解决方式2：使用fastjson"></a>解决方式2：使用fastjson</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--解决hibernate 关联关系死循环问题--&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.alibaba<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>fastjson<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2.59<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure><p>spring-mvc.xml配置</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--开启springMVC注解驱动. SpringMVC整合FastJson:用"最快的json转换工具"替换SpringMVC的默认json转换--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mvc:annotation-driven</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--不使用默认消息转换器 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mvc:message-converters</span> <span class="attr">register-defaults</span>=<span class="string">"false"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--spring消息转换器 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.http.converter.ByteArrayHttpMessageConverter"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.http.converter.BufferedImageHttpMessageConverter"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!--解决@Responcebody中文乱码问题 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.http.converter.StringHttpMessageConverter"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">value</span>=<span class="string">"UTF-8"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--配合fastjson支持 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"defaultCharset"</span> <span class="attr">value</span>=<span class="string">"UTF-8"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"supportedMediaTypes"</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">list</span>&gt;</span></span><br><span class="line">                    <span class="comment">&lt;!--顺序保持这样,避免IE下载出错 --&gt;</span></span><br><span class="line">                    <span class="tag">&lt;<span class="name">value</span>&gt;</span>text/html;charset=UTF-8<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">                    <span class="tag">&lt;<span class="name">value</span>&gt;</span>text/json;charset=UTF-8<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">                    <span class="tag">&lt;<span class="name">value</span>&gt;</span>application/json<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;/<span class="name">list</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"fastJsonConfig"</span> <span class="attr">ref</span>=<span class="string">"fastJsonConfig"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">mvc:message-converters</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mvc:annotation-driven</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--fastJsonConfig --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"fastJsonConfig"</span> <span class="attr">class</span>=<span class="string">"com.alibaba.fastjson.support.config.FastJsonConfig"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--默认编码格式 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"charset"</span> <span class="attr">value</span>=<span class="string">"UTF-8"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"serializerFeatures"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">list</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>WriteNullListAsEmpty<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>WriteDateUseDateFormat<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>PrettyFormat<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>WriteMapNullValue<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>WriteNullStringAsEmpty<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>WriteNullListAsEmpty<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>DisableCircularReferenceDetect<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">list</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--fastjson支持配置结束 --&gt;</span></span><br></pre></td></tr></table></figure><p>使用fastjson注解 @JSONField(serialize=false)</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dept</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> deptId;<span class="comment">// 部门编号</span></span><br><span class="line">    <span class="keyword">private</span> String deptName;<span class="comment">// 部门名称</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@JSONField</span>(serialize=<span class="keyword">false</span>)</span><br><span class="line">    <span class="keyword">private</span> Set&lt;Employee&gt; emps;<span class="comment">// 部门对应多个员工 ，即一对多的关系</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Employee</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> empId;<span class="comment">// 员工的编号</span></span><br><span class="line">    <span class="keyword">private</span> String empName;<span class="comment">// 员工的名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span> salary;<span class="comment">// 员工的薪资</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//@JSONField(serialize=false)</span></span><br><span class="line">    <span class="keyword">private</span> Dept dept;<span class="comment">// 员工和部门的关系</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>效果：</p><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//查询部门信息</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="attr">"deptId"</span>:<span class="number">1</span>,</span><br><span class="line">	<span class="attr">"deptName"</span>:<span class="string">"人事部"</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//查询员工信息</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="attr">"dept"</span>:&#123;</span><br><span class="line">		<span class="attr">"deptId"</span>:<span class="number">1</span>,</span><br><span class="line">		<span class="attr">"deptName"</span>:<span class="string">"人事部"</span></span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="attr">"empId"</span>:<span class="number">1</span>,</span><br><span class="line">	<span class="attr">"empName"</span>:<span class="string">"员工1"</span>,</span><br><span class="line">	<span class="attr">"salary"</span>:<span class="number">1000.0</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><blockquote><p>这种 ，比”解决方式1”更友好 ，只需要单方面取关联数据 ，完美解决序列化时导致的死循环问题</p></blockquote><h4 id="解决方式3：-JsonBackReference"><a href="#解决方式3：-JsonBackReference" class="headerlink" title="解决方式3：@JsonBackReference"></a>解决方式3：@JsonBackReference</h4><p>web.xml配置</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--hibernate延迟加载,配置在所有filter之前 解决无限循环和no Session问题 ，在get方法上使用@JsonBackReference--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">filter</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>hibernateFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-class</span>&gt;</span>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter<span class="tag">&lt;/<span class="name">filter-class</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>sessionFactoryBeanName<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>sessionFactory<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>hibernateFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dispatcher</span>&gt;</span>REQUEST<span class="tag">&lt;/<span class="name">dispatcher</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dispatcher</span>&gt;</span>FORWARD<span class="tag">&lt;/<span class="name">dispatcher</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure><p>使用@JsonBackReference</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dept</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> deptId;<span class="comment">// 部门编号</span></span><br><span class="line">    <span class="keyword">private</span> String deptName;<span class="comment">// 部门名称</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//@JsonBackReference //尽量放到get方法上 ，在序列化时 ，@JsonBackReference的作用相当于@JsonIgnore</span></span><br><span class="line">    <span class="keyword">private</span> Set&lt;Employee&gt; emps;<span class="comment">// 部门对应多个员工 ，即一对多的关系</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Employee</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> empId;<span class="comment">// 员工的编号</span></span><br><span class="line">    <span class="keyword">private</span> String empName;<span class="comment">// 员工的名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span> salary;<span class="comment">// 员工的薪资</span></span><br><span class="line">    </span><br><span class="line">    <span class="meta">@JsonBackReference</span> <span class="comment">//尽量放到get方法上 ，在序列化时 ，@JsonBackReference的作用相当于@JsonIgnore</span></span><br><span class="line">    <span class="keyword">private</span> Dept dept;<span class="comment">// 员工和部门的关系</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>效果：</p><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//查询部门信息</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"deptId"</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">"deptName"</span>: <span class="string">"人事部"</span>,</span><br><span class="line">  <span class="attr">"emps"</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">"empId"</span>: <span class="number">2</span>,</span><br><span class="line">      <span class="attr">"empName"</span>: <span class="string">"员工2"</span>,</span><br><span class="line">      <span class="attr">"salary"</span>: <span class="number">2000</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">"empId"</span>: <span class="number">1</span>,</span><br><span class="line">      <span class="attr">"empName"</span>: <span class="string">"员工1"</span>,</span><br><span class="line">      <span class="attr">"salary"</span>: <span class="number">1000</span></span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//查询员工信息</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"empId"</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">"empName"</span>: <span class="string">"员工1"</span>,</span><br><span class="line">  <span class="attr">"salary"</span>: <span class="number">1000</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><blockquote><p>效果相当于”解决方式2”的效果。</p></blockquote><h3 id="2、双方数据都需要的情况"><a href="#2、双方数据都需要的情况" class="headerlink" title="2、双方数据都需要的情况"></a>2、双方数据都需要的情况</h3><h4 id="解决方式1：返回给前端DTO"><a href="#解决方式1：返回给前端DTO" class="headerlink" title="解决方式1：返回给前端DTO"></a>解决方式1：返回给前端DTO</h4><p>DTO与实体类一样 ，下面是DTO</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//部门DTO</span></span><br><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DeptDTO</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> deptId;<span class="comment">// 部门编号</span></span><br><span class="line">    <span class="keyword">private</span> String deptName;<span class="comment">// 部门名称</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Set&lt;EmployeeDTO&gt; employeeDTOSet;<span class="comment">// 部门对应多个员工 ，即一对多的关系</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//员工DTO</span></span><br><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EmployeeDTO</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> empId;<span class="comment">// 员工的编号</span></span><br><span class="line">    <span class="keyword">private</span> String empName;<span class="comment">// 员工的名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span> salary;<span class="comment">// 员工的薪资</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> DeptDTO deptDTO;<span class="comment">// 员工和部门的关系</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>实体类：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//部门实体类</span></span><br><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dept</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> deptId;<span class="comment">// 部门编号</span></span><br><span class="line">    <span class="keyword">private</span> String deptName;<span class="comment">// 部门名称</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Set&lt;Employee&gt; emps;<span class="comment">// 部门对应多个员工 ，即一对多的关系</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//员工实体类</span></span><br><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@Setter</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Employee</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> empId;<span class="comment">// 员工的编号</span></span><br><span class="line">    <span class="keyword">private</span> String empName;<span class="comment">// 员工的名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span> salary;<span class="comment">// 员工的薪资</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Dept dept;<span class="comment">// 员工和部门的关系</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>使用DTO获取双向数据</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//获取部门</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">getDept</span><span class="params">(<span class="keyword">int</span> deptId)</span></span>&#123;</span><br><span class="line">    Dept dept = <span class="keyword">this</span>.hibernateTemplate.get(Dept<span class="class">.<span class="keyword">class</span>, <span class="title">deptId</span>)</span>;</span><br><span class="line">    System.out.println(<span class="string">"部门名称："</span>+dept.getDeptName());</span><br><span class="line">    Set&lt;Employee&gt; emps = dept.getEmps();</span><br><span class="line">    Iterator&lt;Employee&gt; iterator = emps.iterator();</span><br><span class="line">    Set&lt;EmployeeDTO&gt; employeeDTOSet = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line">    <span class="keyword">while</span> (iterator.hasNext())&#123;</span><br><span class="line">        Employee employee = iterator.next();</span><br><span class="line">        System.out.println(<span class="string">"员工名称："</span>+employee.getEmpName());</span><br><span class="line"></span><br><span class="line">        EmployeeDTO employeeDTO =<span class="keyword">new</span> EmployeeDTO();</span><br><span class="line">        employeeDTO.setEmpId(employee.getEmpId());</span><br><span class="line">        employeeDTO.setEmpName(employee.getEmpName());</span><br><span class="line">        employeeDTO.setSalary(employee.getSalary());</span><br><span class="line">        employeeDTOSet.add(employeeDTO);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    DeptDTO deptDTO = <span class="keyword">new</span> DeptDTO();</span><br><span class="line">    deptDTO.setDeptId(dept.getDeptId());</span><br><span class="line">    deptDTO.setDeptName(dept.getDeptName());</span><br><span class="line">    deptDTO.setEmployeeDTOSet(employeeDTOSet);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> deptDTO;</span><br><span class="line">    <span class="comment">//return dept;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//获取所有部门</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">getAllDept</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.hibernateTemplate.loadAll(Dept<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//获取员工</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">getEmployee</span><span class="params">(<span class="keyword">int</span> empId)</span></span>&#123;</span><br><span class="line">    Employee employee = <span class="keyword">this</span>.hibernateTemplate.get(Employee<span class="class">.<span class="keyword">class</span>, <span class="title">empId</span>)</span>;</span><br><span class="line">    System.out.println(<span class="string">"员工名称："</span>+employee.getEmpName());</span><br><span class="line">    Dept dept = employee.getDept();</span><br><span class="line">    System.out.println(<span class="string">"员工【 "</span>+employee.getEmpName()+<span class="string">" 】属于 部门："</span>+dept.getDeptName());</span><br><span class="line"></span><br><span class="line">    EmployeeDTO employeeDTO = <span class="keyword">new</span> EmployeeDTO();</span><br><span class="line">    employeeDTO.setEmpId(employee.getEmpId());</span><br><span class="line">    employeeDTO.setEmpName(employee.getEmpName());</span><br><span class="line">    employeeDTO.setSalary(employee.getSalary());</span><br><span class="line"></span><br><span class="line">    DeptDTO deptDTO = <span class="keyword">new</span> DeptDTO();</span><br><span class="line">    deptDTO.setDeptId(employee.getDept().getDeptId());</span><br><span class="line">    deptDTO.setDeptName(employee.getDept().getDeptName());</span><br><span class="line">    employeeDTO.setDeptDTO(deptDTO);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> employeeDTO;</span><br><span class="line">    <span class="comment">//return employee;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>效果：</p><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//获取部门信息</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"deptId"</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">"deptName"</span>: <span class="string">"人事部"</span>,</span><br><span class="line">  <span class="attr">"employeeDTOSet"</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">"empId"</span>: <span class="number">2</span>,</span><br><span class="line">      <span class="attr">"empName"</span>: <span class="string">"员工2"</span>,</span><br><span class="line">      <span class="attr">"salary"</span>: <span class="number">2000</span>,</span><br><span class="line">      <span class="attr">"deptDTO"</span>: <span class="literal">null</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">"empId"</span>: <span class="number">1</span>,</span><br><span class="line">      <span class="attr">"empName"</span>: <span class="string">"员工1"</span>,</span><br><span class="line">      <span class="attr">"salary"</span>: <span class="number">1000</span>,</span><br><span class="line">      <span class="attr">"deptDTO"</span>: <span class="literal">null</span></span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//获取员工信息</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"empId"</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">"empName"</span>: <span class="string">"员工1"</span>,</span><br><span class="line">  <span class="attr">"salary"</span>: <span class="number">1000</span>,</span><br><span class="line">  <span class="attr">"deptDTO"</span>: &#123;</span><br><span class="line">    <span class="attr">"deptId"</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">"deptName"</span>: <span class="string">"人事部"</span>,</span><br><span class="line">    <span class="attr">"employeeDTOSet"</span>: <span class="literal">null</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><blockquote><p>当然”只有一方需要数据” ，也是可以使用这种DTO方式的 ，这种方式比较全能 ，推荐使用。</p></blockquote></div><div class="popular-posts-header"><p style="font-size:18px;color:red;margin:0 0 5px 0">相关文章推荐：</p></div><ul class="popular-posts"><li class="popular-posts-item"><div class="popular-posts-title"><a href="\posts\4087415796.html" rel="bookmark">Hibernate-和-JPA主键生成策略</a></div></li></ul><div><div style="text-align:center;color:#ccc;font-size:14px">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div></div><div class="reward-container"><div><p style="font-size:14px;color:#34495e;margin:0 0 5px 0">赞赏一下吧～ 还可以关注公众号订阅最新内容</p></div><button disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">打赏</button><div id="qr" style="display:none"><div style="display:inline-block"><img src="/my-images/WeChat.png" alt="宇宙小神特别萌 微信支付"><p>微信支付</p></div><div style="display:inline-block"><img src="/my-images/Alipay.png" alt="宇宙小神特别萌 支付宝"><p>支付宝</p></div></div></div><footer class="post-footer"><div class="post-tags"><a href="/tags/Hibernate/" rel="tag"><i class="fa fa-tag"></i> Hibernate</a></div><div class="post-nav"><div class="post-nav-item"><a href="/posts/4087415796.html" rel="prev" title="Hibernate-和-JPA主键生成策略"><i class="fa fa-chevron-left"></i> Hibernate-和-JPA主键生成策略</a></div><div class="post-nav-item"><a href="/posts/1424390860.html" rel="next" title="docker安装遇到的问题">docker安装遇到的问题 <i class="fa fa-chevron-right"></i></a></div></div></footer></article></div></div><div class="comments" id="valine-comments"></div><script>window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }</script></div><div class="toggle sidebar-toggle"><span class="toggle-line toggle-line-first"></span> <span class="toggle-line toggle-line-middle"></span> <span class="toggle-line toggle-line-last"></span></div><aside class="sidebar"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc">文章目录</li><li class="sidebar-nav-overview">站点概览</li></ul><div class="post-toc-wrap sidebar-panel"><div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、no-session-原因及解决"><span class="nav-text">一、no session 原因及解决</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1、原因：load-延迟查询引起noSession问题"><span class="nav-text">1、原因：load()延迟查询引起noSession问题</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2、原因：没有开启使用注解事务-或者已经开启注解事务但并未使用"><span class="nav-text">2、原因：没有开启使用注解事务(或者已经开启注解事务但并未使用)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3、原因：手动配置事务时-，propagation的值并未含有事务环境"><span class="nav-text">3、原因：手动配置事务时 ，propagation的值并未含有事务环境</span></a></li></ol></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#二、懒加载出现死循环"><span class="nav-text">二、懒加载出现死循环</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1、只有一方需要数据"><span class="nav-text">1、只有一方需要数据</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#解决方式1：使用-JsonIgnore"><span class="nav-text">解决方式1：使用@JsonIgnore</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#解决方式2：使用fastjson"><span class="nav-text">解决方式2：使用fastjson</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#解决方式3：-JsonBackReference"><span class="nav-text">解决方式3：@JsonBackReference</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2、双方数据都需要的情况"><span class="nav-text">2、双方数据都需要的情况</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#解决方式1：返回给前端DTO"><span class="nav-text">解决方式1：返回给前端DTO</span></a></li></ol></li></ol></li></div></div><div class="site-overview-wrap sidebar-panel"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"><img class="site-author-image" itemprop="image" alt="宇宙小神特别萌" src="/my-images/avatar.gif"><p class="site-author-name" itemprop="name">宇宙小神特别萌</p><div class="site-description" itemprop="description">人生就是一次幸运的旅行！</div></div><div class="site-state-wrap motion-element"><nav class="site-state"><div class="site-state-item site-state-posts"><a href="/archives/"><span class="site-state-item-count">116</span> <span class="site-state-item-name">文章</span></a></div><div class="site-state-item site-state-tags"><a href="/tags/"><span class="site-state-item-count">27</span> <span class="site-state-item-name">标签</span></a></div></nav></div><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="https://github.com/zhengjiaao" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;zhengjiaao" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a> </span><span class="links-of-author-item"><a href="https://www.jianshu.com/u/70d69269bd09" title="简书 → https:&#x2F;&#x2F;www.jianshu.com&#x2F;u&#x2F;70d69269bd09" rel="noopener" target="_blank"><i class="fa fa-fw fa-book"></i>简书</a> </span><span class="links-of-author-item"><a href="/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-fw fa-rss"></i>RSS</a></span></div><div class="links-of-blogroll motion-element"><div class="links-of-blogroll-title"><i class="fa fa-fw fa-link"></i> 推荐阅读</div><ul class="links-of-blogroll-list"><li class="links-of-blogroll-item"><a href="https://github.com/spring-projects" title="https:&#x2F;&#x2F;github.com&#x2F;spring-projects" rel="noopener" target="_blank">spring-projects</a></li><li class="links-of-blogroll-item"><a href="http://www.alloyteam.com/nav/" title="http:&#x2F;&#x2F;www.alloyteam.com&#x2F;nav&#x2F;" rel="noopener" target="_blank">Web前端导航</a></li><li class="links-of-blogroll-item"><a href="http://www.chuangzaoshi.com/code" title="http:&#x2F;&#x2F;www.chuangzaoshi.com&#x2F;code" rel="noopener" target="_blank">创造狮导航</a></li></ul></div></div></div></aside><div id="sidebar-dimmer"></div></div></main><footer class="footer"><div class="footer-inner"><div class="copyright">&copy; <span itemprop="copyrightYear">2020</span> <span class="with-love"><i class="fa fa-heart"></i> </span><span class="author" itemprop="copyrightHolder">宇宙小神特别萌</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-area-chart"></i> </span><span title="站点总字数">1.2m</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-coffee"></i> </span><span title="站点阅读时长">17:41</span></div><div class="busuanzi-count"><script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span class="post-meta-item" id="busuanzi_container_site_uv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-user"></i> </span><span class="site-uv" title="总访客量"><span id="busuanzi_value_site_uv"></span> </span></span><span class="post-meta-divider">|</span> <span class="post-meta-item" id="busuanzi_container_site_pv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-eye"></i> </span><span class="site-pv" title="总访问量"><span id="busuanzi_value_site_pv"></span></span></span></div></div></footer></div><script src="//cdn.jsdelivr.net/npm/animejs@3.1.0/lib/anime.min.js"></script><script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script><script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/velocity/1.2.1/velocity.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/velocity/1.2.1/velocity.ui.min.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script><script>!function(){var t=document.createElement("script"),e=window.location.protocol.split(":")[0];t.src="https"===e?"https://zz.bdstatic.com/linksubmit/push.js":"http://push.zhanzhang.baidu.com/push.js";var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(t,s)}()</script><script src="/js/local-search.js"></script><script>NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//cdnjs.cloudflare.com/ajax/libs/valine/1.3.10/Valine.min.js', () => {
    <!--var GUEST = ['nick', 'mail', 'link'];-->
    var GUEST = ['nick', 'mail'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el: '#valine-comments',
      verify: false,
      notify: false,
      appId: 'OuyHeA0XGL8hK4vgbqL0iERx-gzGzoHsz',
      appKey: 'L58VglKmWULcGK2W2AN7kWzM',
      placeholder: "留下邮箱，有回复时你将收到提醒，邮箱不会被公开。",
      avatar: 'wavatar',
      meta: guest,
      pageSize: '10' || 10,
      visitor: true,
      lang: 'zh-cn' || 'zh-cn',
      path: location.pathname,
      recordIP: true,
      serverURLs: ''
    });
  }, window.Valine);
});</script><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({pluginRootPath:"live2dw/",pluginJsPath:"lib/",pluginModelPath:"assets/",tagMode:!1,model:{jsonPath:"/live2dw/assets/wanko.model.json"},display:{position:"right",width:150,height:300},mobile:{show:!1},log:!1})</script></body><script type="text/javascript" src="/js/src/activetitle.js"></script></html><!-- rebuild by neat -->